<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\RoomsResource;
use App\Models\Consume;
use App\Models\Episode;
use App\Models\History;
use App\Models\Like;
use App\Models\Trace;
use App\Models\Type;
use App\Models\User;
use App\Models\Video;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Room;
use Illuminate\Http\Request;

class VideoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request,Video $video)
    {
        $query=$video->newQuery();
        if($request->has('type') && !empty($request->type)){
            $query->whereJsonContains('type_id',$request->type);
        }
        $list=$query->where('status',1)
            ->paginate(10);
        if($list->isEmpty()){
            return $this->error('数据查询为空');
        }
        return $this->success('success',$list);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /***
     * 获取单个视频详情
     * 验证消费
     * 加入消费记录
     * 加入历史记录
     *
     * @param Request $request
     * @param Video $video
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request,Video $video)
    {
        try {
            DB::beginTransaction();
            $query = $video->newQuery();
            if ($request->has('id') && !empty($request->id)) {
                $query->where('id', $request->id);
            }
            if ($request->has('episodes_id') && !empty($request->episodes_id)) {
                $query->where('episodes_id', $request->episodes_id);
            }
            if ($request->has('sort_id') && !empty($request->sort_id)) {
                $query->where('sort', $request->sort_id);
            }

            $list = $query->where('status', 1)
//                ->orderBy('sort')
                ->select('id', 'name', 'is_fee', 'cover', 'sort', 'price', 'episodes_id', 'url', 'desc')
                ->first();
            if (!$list) {
                return $this->error('数据查询为空');
            }
//            $ep = Episode::find($list['episodes_id']);
            $userxf = Consume::where(['user_id' => $this->user->id, 'video_id' => $list['episodes_id'], 'sort' => $list['sort']])->first();
            //验证爽豆
            if ($list['is_fee'] && empty($userxf)) {//收费
                if (!isVip($this->user->vip_end_time)) {
                    if ($this->user->integral == 0 || $this->user->integral < $list['price']) {//本身爽豆不小于0 本身爽豆不低于单条视频价格
                        return $this->error('爽豆不足', ['price' => $list['price']]);
                    } else {
                        if (User::integral($this->user->id, -($list['price']), '单集消费', 'BUY_VIDEO')) {
                            User::addConsume($this->user->id, $this->user->mps_id, $list['episodes_id'], $list['sort'], $list['price']);//消费记录
                        }

                    }
                }
            }
            $this->joinHistory($list);
            $list['cover'] = dealUrl($list['cover']);
            $list['is_pay'] = !empty($userxf) ? 1 : 0;
            $list['is_zui'] = Trace::where('episodes_id', $list['episodes_id'])->where('user_id', $this->user->id)->exists() ? 1 : 0;
            $list['zui_count_num'] = Trace::where('episodes_id', $list['episodes_id'])->count();
            $list['is_like'] = Like::where('user_id', $this->user->id)->where('episodes_id', $list['episodes_id'])->where('sort_id', $list['sort'])->exists() ? 1 : 0;
            $list['like_count_num'] = Like::where('episodes_id', $list['episodes_id'])->count();
            DB::commit();
            return $this->success('success', $list);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
    }

    public function gettype(Request $request,Type $type)
    {
        if(!$request->has('type') || empty($request->type)){
            return $this->error('数据错误');
        }else{
            $query=$type->newQuery();
            $query->where('identify',$request->type);
            $query->where('is_xian', 1);
            $query->where('parent_id','!=',0);
            $query->select('id','title');
            $query->orderBy('order');
            return $this->success('数据获取成功',$query->get());
        }

    }

    /***
     * 加入历史记录
     * @param $list
     */
    private function joinHistory($list){
        if($this->user){
            $data=[
                'user_id'=>$this->user->id,
                'traces_id'=>$list['episodes_id'],
            ];
            History::updateOrCreate($data, ['video_id' => $list['id']]);
        }
    }
}
